{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Installation\n",
    "! pip install smolagents\n",
    "# To install from source instead of the last release, comment the command above and uncomment the following one.\n",
    "# ! pip install git+https://github.com/huggingface/smolagents.git"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Agents - Guided tour"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "In this guided visit, you will learn how to build an agent, how to run it, and how to customize it to make it work better for your use-case."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Choosing an agent type: CodeAgent or ToolCallingAgent"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "`smolagents` comes with two agent classes: [CodeAgent](https://huggingface.co/docs/smolagents/main/en/reference/agents#smolagents.CodeAgent) and [ToolCallingAgent](https://huggingface.co/docs/smolagents/main/en/reference/agents#smolagents.ToolCallingAgent), which represent two different paradigms for how agents interact with tools.\n",
    "The key difference lies in how actions are specified and executed: code generation vs structured tool calling.\n",
    "\n",
    "- [CodeAgent](https://huggingface.co/docs/smolagents/main/en/reference/agents#smolagents.CodeAgent) generates tool calls as Python code snippets.\n",
    "  - The code is executed either locally (potentially unsecure) or in a secure sandbox.\n",
    "  - Tools are exposed as Python functions (via bindings).\n",
    "  - Example of tool call:\n",
    "    ```py\n",
    "    result = search_docs(\"What is the capital of France?\")\n",
    "    print(result)\n",
    "    ```\n",
    "  - Strengths:\n",
    "    - Highly expressive: Allows for complex logic and control flow and can combine tools, loop, transform, reason.\n",
    "    - Flexible: No need to predefine every possible action, can dynamically generate new actions/tools.\n",
    "    - Emergent reasoning: Ideal for multi-step problems or dynamic logic.\n",
    "  - Limitations\n",
    "    - Risk of errors: Must handle syntax errors, exceptions.\n",
    "    - Less predictable: More prone to unexpected or unsafe outputs.\n",
    "    - Requires secure execution environment.\n",
    "\n",
    "- [ToolCallingAgent](https://huggingface.co/docs/smolagents/main/en/reference/agents#smolagents.ToolCallingAgent) writes tool calls as structured JSON.\n",
    "  - This is the common format used in many frameworks (OpenAI API), allowing for structured tool interactions without code execution.\n",
    "  - Tools are defined with a JSON schema: name, description, parameter types, etc.\n",
    "  - Example of tool call:\n",
    "    ```json\n",
    "    {\n",
    "      \"tool_call\": {\n",
    "        \"name\": \"search_docs\",\n",
    "        \"arguments\": {\n",
    "          \"query\": \"What is the capital of France?\"\n",
    "        }\n",
    "      }\n",
    "    }\n",
    "    ```\n",
    "  - Strengths:\n",
    "    - Reliable: Less prone to hallucination, outputs are structured and validated.\n",
    "    - Safe: Arguments are strictly validated, no risk of arbitrary code running.\n",
    "    - Interoperable: Easy to map to external APIs or services.\n",
    "  - Limitations:\n",
    "    - Low expressivity: Can't easily combine or transform results dynamically, or perform complex logic or control flow.\n",
    "    - Inflexible: Must define all possible actions in advance, limited to predefined tools.\n",
    "    - No code synthesis: Limited to tool capabilities.\n",
    "\n",
    "When to use which agent type:\n",
    "- Use [CodeAgent](https://huggingface.co/docs/smolagents/main/en/reference/agents#smolagents.CodeAgent) when:\n",
    "  - You need reasoning, chaining, or dynamic composition.\n",
    "  - Tools are functions that can be combined (e.g., parsing + math + querying).\n",
    "  - Your agent is a problem solver or programmer.\n",
    "\n",
    "- Use [ToolCallingAgent](https://huggingface.co/docs/smolagents/main/en/reference/agents#smolagents.ToolCallingAgent) when:\n",
    "  - You have simple, atomic tools (e.g., call an API, fetch a document).\n",
    "  - You want high reliability and clear validation.\n",
    "  - Your agent is like a dispatcher or controller."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## CodeAgent"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "[CodeAgent](https://huggingface.co/docs/smolagents/main/en/reference/agents#smolagents.CodeAgent) generates Python code snippets to perform actions and solve tasks.\n",
    "\n",
    "By default, the Python code execution is done in your local environment.\n",
    "This should be safe because the only functions that can be called are the tools you provided (especially if it's only tools by Hugging Face) and a set of predefined safe functions like `print` or functions from the `math` module, so you're already limited in what can be executed.\n",
    "\n",
    "The Python interpreter also doesn't allow imports by default outside of a safe list, so all the most obvious attacks shouldn't be an issue.\n",
    "You can authorize additional imports by passing the authorized modules as a list of strings in argument `additional_authorized_imports` upon initialization of your [CodeAgent](https://huggingface.co/docs/smolagents/main/en/reference/agents#smolagents.CodeAgent):"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "model = InferenceClientModel()\n",
    "agent = CodeAgent(tools=[], model=model, additional_authorized_imports=['requests', 'bs4'])\n",
    "agent.run(\"Could you get me the title of the page at url 'https://huggingface.co/blog'?\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Additionally, as an extra security layer, access to submodule is forbidden by default, unless explicitly authorized within the import list.\n",
    "For instance, to access the `numpy.random` submodule, you need to add `'numpy.random'` to the `additional_authorized_imports` list.\n",
    "This could also be authorized by using `numpy.*`, which will allow `numpy` as well as any subpackage like `numpy.random` and its own subpackages.\n",
    "\n",
    "> [!WARNING]\n",
    "> The LLM can generate arbitrary code that will then be executed: do not add any unsafe imports!\n",
    "\n",
    "The execution will stop at any code trying to perform an illegal operation or if there is a regular Python error with the code generated by the agent.\n",
    "\n",
    "You can also use [Blaxel](https://blaxel.ai), [E2B](https://e2b.dev/docs#what-is-e2-b), or Docker instead of a local Python interpreter. For Blaxel, first [set the `BL_API_KEY` and `BL_WORKSPACE` environment variables](https://app.blaxel.ai/profile/security) and then pass `executor_type=\"blaxel\"` upon agent initialization. For E2B, first [set the `E2B_API_KEY` environment variable](https://e2b.dev/dashboard?tab=keys) and then pass `executor_type=\"e2b\"`. For Docker, pass `executor_type=\"docker\"`.\n",
    "\n",
    "\n",
    "> [!TIP]\n",
    "> Learn more about code execution [in this tutorial](https://huggingface.co/docs/smolagents/main/en/tutorials/secure_code_execution)."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### ToolCallingAgent"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "[ToolCallingAgent](https://huggingface.co/docs/smolagents/main/en/reference/agents#smolagents.ToolCallingAgent) outputs JSON tool calls, which is the common format used in many frameworks (OpenAI API), allowing for structured tool interactions without code execution. We utilize the built-in WebSearchTool (from the smolagents toolkit extra, which will be described in more detail later) to enable our agent to perform web searches.   \n",
    "\n",
    "It works much in the same way like [CodeAgent](https://huggingface.co/docs/smolagents/main/en/reference/agents#smolagents.CodeAgent), of course without `additional_authorized_imports` since it doesn't execute code:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from smolagents import ToolCallingAgent, WebSearchTool\n",
    "\n",
    "agent = ToolCallingAgent(tools=[WebSearchTool()], model=model)\n",
    "agent.run(\"Could you get me the title of the page at url 'https://huggingface.co/blog'?\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Using the CLI"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "You can quickly get started with smolagents using the command line interface:\n",
    "\n",
    "```bash\n",
    "# Run with direct prompt and options\n",
    "smolagent \"Plan a trip to Tokyo, Kyoto and Osaka between Mar 28 and Apr 7.\"  --model-type \"InferenceClientModel\" --model-id \"Qwen/Qwen2.5-Coder-32B-Instruct\" --imports \"pandas numpy\" --tools \"web_search\"\n",
    "\n",
    "# Run in interactive mode: launches when no prompt is provided, will guide you through argument selection\n",
    "smolagent\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Building your agent"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "To initialize a minimal agent, you need at least these two arguments:\n",
    "\n",
    "- `model`, a text-generation model to power your agent - because the agent is different from a simple LLM, it is a system that uses a LLM as its engine. You can use any of these options:\n",
    "    - [TransformersModel](https://huggingface.co/docs/smolagents/main/en/reference/models#smolagents.TransformersModel) takes a pre-initialized `transformers` pipeline to run inference on your local machine using `transformers`.\n",
    "    - [InferenceClientModel](https://huggingface.co/docs/smolagents/main/en/reference/models#smolagents.InferenceClientModel) leverages a `huggingface_hub.InferenceClient` under the hood and supports all Inference Providers on the Hub: Cerebras, Cohere, Fal, Fireworks, HF-Inference, Hyperbolic, Nebius, Novita, Replicate, SambaNova, Together, and more.\n",
    "    - [LiteLLMModel](https://huggingface.co/docs/smolagents/main/en/reference/models#smolagents.LiteLLMModel) similarly lets you call 100+ different models and providers through [LiteLLM](https://docs.litellm.ai/)!\n",
    "    - [AzureOpenAIModel](https://huggingface.co/docs/smolagents/main/en/reference/models#smolagents.AzureOpenAIModel) allows you to use OpenAI models deployed in [Azure](https://azure.microsoft.com/en-us/products/ai-services/openai-service).\n",
    "    - [AmazonBedrockModel](https://huggingface.co/docs/smolagents/main/en/reference/models#smolagents.AmazonBedrockModel) allows you to use Amazon Bedrock in [AWS](https://aws.amazon.com/bedrock/?nc1=h_ls).\n",
    "    - [MLXModel](https://huggingface.co/docs/smolagents/main/en/reference/models#smolagents.MLXModel) creates a [mlx-lm](https://pypi.org/project/mlx-lm/) pipeline to run inference on your local machine.\n",
    "\n",
    "- `tools`, a list of `Tools` that the agent can use to solve the task. It can be an empty list. You can also add the default toolbox on top of your `tools` list by defining the optional argument `add_base_tools=True`.\n",
    "\n",
    "Once you have these two arguments, `tools` and `model`,  you can create an agent and run it. You can use any LLM you'd like, either through [Inference Providers](https://huggingface.co/blog/inference-providers), [transformers](https://github.com/huggingface/transformers/), [ollama](https://ollama.com/), [LiteLLM](https://www.litellm.ai/), [Azure OpenAI](https://azure.microsoft.com/en-us/products/ai-services/openai-service), [Amazon Bedrock](https://aws.amazon.com/bedrock/?nc1=h_ls), or [mlx-lm](https://pypi.org/project/mlx-lm/).\n",
    "\n",
    "All model classes support passing additional keyword arguments (like `temperature`, `max_tokens`, `top_p`, etc.) directly at instantiation time.\n",
    "These parameters are automatically forwarded to the underlying model's completion calls, allowing you to configure model behavior such as creativity, response length, and sampling strategies.\n",
    "\n",
    "<hfoptions id=\"Pick a LLM\">\n",
    "<hfoption id=\"Inference Providers\">\n",
    "\n",
    "Inference Providers need a `HF_TOKEN` to authenticate, but a free HF account already comes with included credits. Upgrade to PRO to raise your included credits.\n",
    "\n",
    "To access gated models or rise your rate limits with a PRO account, you need to set the environment variable `HF_TOKEN` or pass `token` variable upon initialization of `InferenceClientModel`. You can get your token from your [settings page](https://huggingface.co/settings/tokens)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from smolagents import CodeAgent, InferenceClientModel\n",
    "\n",
    "model_id = \"meta-llama/Llama-3.3-70B-Instruct\"\n",
    "\n",
    "model = InferenceClientModel(model_id=model_id, token=\"<YOUR_HUGGINGFACEHUB_API_TOKEN>\") # You can choose to not pass any model_id to InferenceClientModel to use a default model\n",
    "# you can also specify a particular provider e.g. provider=\"together\" or provider=\"sambanova\"\n",
    "agent = CodeAgent(tools=[], model=model, add_base_tools=True)\n",
    "\n",
    "agent.run(\n",
    "    \"Could you give me the 118th number in the Fibonacci sequence?\",\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "</hfoption>\n",
    "<hfoption id=\"Local Transformers Model\">"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# !pip install 'smolagents[transformers]'\n",
    "from smolagents import CodeAgent, TransformersModel\n",
    "\n",
    "model_id = \"meta-llama/Llama-3.2-3B-Instruct\"\n",
    "\n",
    "model = TransformersModel(model_id=model_id)\n",
    "agent = CodeAgent(tools=[], model=model, add_base_tools=True)\n",
    "\n",
    "agent.run(\n",
    "    \"Could you give me the 118th number in the Fibonacci sequence?\",\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "</hfoption>\n",
    "<hfoption id=\"OpenAI or Anthropic API\">\n",
    "\n",
    "To use `LiteLLMModel`, you need to set the environment variable `ANTHROPIC_API_KEY` or `OPENAI_API_KEY`, or pass `api_key` variable upon initialization."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# !pip install 'smolagents[litellm]'\n",
    "from smolagents import CodeAgent, LiteLLMModel\n",
    "\n",
    "model = LiteLLMModel(model_id=\"anthropic/claude-3-5-sonnet-latest\", api_key=\"YOUR_ANTHROPIC_API_KEY\") # Could use 'gpt-4o'\n",
    "agent = CodeAgent(tools=[], model=model, add_base_tools=True)\n",
    "\n",
    "agent.run(\n",
    "    \"Could you give me the 118th number in the Fibonacci sequence?\",\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "</hfoption>\n",
    "<hfoption id=\"Ollama\">"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# !pip install 'smolagents[litellm]'\n",
    "from smolagents import CodeAgent, LiteLLMModel\n",
    "\n",
    "model = LiteLLMModel(\n",
    "    model_id=\"ollama_chat/llama3.2\", # This model is a bit weak for agentic behaviours though\n",
    "    api_base=\"http://localhost:11434\", # replace with 127.0.0.1:11434 or remote open-ai compatible server if necessary\n",
    "    api_key=\"YOUR_API_KEY\", # replace with API key if necessary\n",
    "    num_ctx=8192, # ollama default is 2048 which will fail horribly. 8192 works for easy tasks, more is better. Check https://huggingface.co/spaces/NyxKrage/LLM-Model-VRAM-Calculator to calculate how much VRAM this will need for the selected model.\n",
    ")\n",
    "\n",
    "agent = CodeAgent(tools=[], model=model, add_base_tools=True)\n",
    "\n",
    "agent.run(\n",
    "    \"Could you give me the 118th number in the Fibonacci sequence?\",\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "</hfoption>\n",
    "<hfoption id=\"Azure OpenAI\">\n",
    "\n",
    "To connect to Azure OpenAI, you can either use `AzureOpenAIModel` directly, or use `LiteLLMModel` and configure it accordingly.\n",
    "\n",
    "To initialize an instance of `AzureOpenAIModel`, you need to pass your model deployment name and then either pass the `azure_endpoint`, `api_key`, and `api_version` arguments, or set the environment variables `AZURE_OPENAI_ENDPOINT`, `AZURE_OPENAI_API_KEY`, and `OPENAI_API_VERSION`."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# !pip install 'smolagents[openai]'\n",
    "from smolagents import CodeAgent, AzureOpenAIModel\n",
    "\n",
    "model = AzureOpenAIModel(model_id=\"gpt-4o-mini\")\n",
    "agent = CodeAgent(tools=[], model=model, add_base_tools=True)\n",
    "\n",
    "agent.run(\n",
    "    \"Could you give me the 118th number in the Fibonacci sequence?\",\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Similarly, you can configure `LiteLLMModel` to connect to Azure OpenAI as follows:\n",
    "\n",
    "- pass your model deployment name as `model_id`, and make sure to prefix it with `azure/`\n",
    "- make sure to set the environment variable `AZURE_API_VERSION`\n",
    "- either pass the `api_base` and `api_key` arguments, or set the environment variables `AZURE_API_KEY`, and `AZURE_API_BASE`"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import os\n",
    "from smolagents import CodeAgent, LiteLLMModel\n",
    "\n",
    "AZURE_OPENAI_CHAT_DEPLOYMENT_NAME=\"gpt-35-turbo-16k-deployment\" # example of deployment name\n",
    "\n",
    "os.environ[\"AZURE_API_KEY\"] = \"\" # api_key\n",
    "os.environ[\"AZURE_API_BASE\"] = \"\" # \"https://example-endpoint.openai.azure.com\"\n",
    "os.environ[\"AZURE_API_VERSION\"] = \"\" # \"2024-10-01-preview\"\n",
    "\n",
    "model = LiteLLMModel(model_id=\"azure/\" + AZURE_OPENAI_CHAT_DEPLOYMENT_NAME)\n",
    "agent = CodeAgent(tools=[], model=model, add_base_tools=True)\n",
    "\n",
    "agent.run(\n",
    "   \"Could you give me the 118th number in the Fibonacci sequence?\",\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "</hfoption>\n",
    "<hfoption id=\"Amazon Bedrock\">\n",
    "\n",
    "The `AmazonBedrockModel` class provides native integration with Amazon Bedrock, allowing for direct API calls and comprehensive configuration.\n",
    "\n",
    "Basic Usage:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# !pip install 'smolagents[bedrock]'\n",
    "from smolagents import CodeAgent, AmazonBedrockModel\n",
    "\n",
    "model = AmazonBedrockModel(model_id=\"anthropic.claude-3-sonnet-20240229-v1:0\")\n",
    "agent = CodeAgent(tools=[], model=model, add_base_tools=True)\n",
    "\n",
    "agent.run(\n",
    "    \"Could you give me the 118th number in the Fibonacci sequence?\",\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Advanced Configuration:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import boto3\n",
    "from smolagents import AmazonBedrockModel\n",
    "\n",
    "# Create a custom Bedrock client\n",
    "bedrock_client = boto3.client(\n",
    "    'bedrock-runtime',\n",
    "    region_name='us-east-1',\n",
    "    aws_access_key_id='YOUR_ACCESS_KEY',\n",
    "    aws_secret_access_key='YOUR_SECRET_KEY'\n",
    ")\n",
    "\n",
    "additional_api_config = {\n",
    "    \"inferenceConfig\": {\n",
    "        \"maxTokens\": 3000\n",
    "    },\n",
    "    \"guardrailConfig\": {\n",
    "        \"guardrailIdentifier\": \"identify1\",\n",
    "        \"guardrailVersion\": 'v1'\n",
    "    },\n",
    "}\n",
    "\n",
    "# Initialize with comprehensive configuration\n",
    "model = AmazonBedrockModel(\n",
    "    model_id=\"us.amazon.nova-pro-v1:0\",\n",
    "    client=bedrock_client,  # Use custom client\n",
    "    **additional_api_config\n",
    ")\n",
    "\n",
    "agent = CodeAgent(tools=[], model=model, add_base_tools=True)\n",
    "\n",
    "agent.run(\n",
    "    \"Could you give me the 118th number in the Fibonacci sequence?\",\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Using LiteLLMModel:\n",
    "\n",
    "Alternatively, you can use `LiteLLMModel` with Bedrock models:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from smolagents import LiteLLMModel, CodeAgent\n",
    "\n",
    "model = LiteLLMModel(model_name=\"bedrock/anthropic.claude-3-sonnet-20240229-v1:0\")\n",
    "agent = CodeAgent(tools=[], model=model)\n",
    "\n",
    "agent.run(\"Explain the concept of quantum computing\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "</hfoption>\n",
    "<hfoption id=\"mlx-lm\">"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# !pip install 'smolagents[mlx-lm]'\n",
    "from smolagents import CodeAgent, MLXModel\n",
    "\n",
    "mlx_model = MLXModel(\"mlx-community/Qwen2.5-Coder-32B-Instruct-4bit\")\n",
    "agent = CodeAgent(model=mlx_model, tools=[], add_base_tools=True)\n",
    "\n",
    "agent.run(\"Could you give me the 118th number in the Fibonacci sequence?\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "</hfoption>\n",
    "</hfoptions>"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Model parameter management"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "When initializing models, you can pass keyword arguments that will be forwarded as completion parameters to the\n",
    "underlying model API during inference.\n",
    "\n",
    "For fine-grained control over parameter handling, the `REMOVE_PARAMETER` sentinel value allows you to explicitly exclude\n",
    "parameters that might otherwise be set by default or passed through elsewhere:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from smolagents import OpenAIModel, REMOVE_PARAMETER\n",
    "\n",
    "# Remove \"stop\" parameter\n",
    "model = OpenAIModel(\n",
    "    model_id=\"gpt-5\",\n",
    "    stop=REMOVE_PARAMETER,  # Ensures \"stop\" is not included in API calls\n",
    "    temperature=0.7\n",
    ")\n",
    "\n",
    "agent = CodeAgent(tools=[], model=model, add_base_tools=True)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "This is particularly useful when:\n",
    "- You want to override default parameters that might be applied automatically\n",
    "- You need to ensure certain parameters are completely excluded from API calls\n",
    "- You want to let the model provider use their own defaults for specific parameters"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Advanced agent configuration"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Customizing agent termination conditions"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "By default, an agent continues running until it calls the `final_answer` function or reaches the maximum number of steps.\n",
    "The `final_answer_checks` parameter gives you more control over when and how an agent terminates its execution:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from smolagents import CodeAgent, InferenceClientModel\n",
    "\n",
    "# Define a custom final answer check function\n",
    "def is_integer(final_answer: str, agent_memory=None) -> bool:\n",
    "    \"\"\"Return True if final_answer is an integer.\"\"\"\n",
    "    try:\n",
    "        int(final_answer)\n",
    "        return True\n",
    "    except ValueError:\n",
    "        return False\n",
    "\n",
    "# Initialize agent with custom final answer check\n",
    "agent = CodeAgent(\n",
    "    tools=[],\n",
    "    model=InferenceClientModel(),\n",
    "    final_answer_checks=[is_integer]\n",
    ")\n",
    "\n",
    "agent.run(\"Calculate the least common multiple of 3 and 7\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The `final_answer_checks` parameter accepts a list of functions that each:\n",
    "- Take the agent's final_answer and the agent itself as parameters\n",
    "- Return a boolean indicating whether the final_answer is valid (True) or not (False)\n",
    "\n",
    "If any function returns `False`, the agent will log the error message and continue the run.\n",
    "This validation mechanism enables:\n",
    "- Enforcing output format requirements (e.g., ensuring numeric answers for math problems)\n",
    "- Implementing domain-specific validation rules\n",
    "- Creating more robust agents that validate their own outputs"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Inspecting an agent run"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Here are a few useful attributes to inspect what happened after a run:\n",
    "- `agent.logs` stores the fine-grained logs of the agent. At every step of the agent's run, everything gets stored in a dictionary that then is appended to `agent.logs`.\n",
    "- Running `agent.write_memory_to_messages()` writes the agent's memory as list of chat messages for the Model to view. This method goes over each step of the log and only stores what it's interested in as a message: for instance, it will save the system prompt and task in separate messages, then for each step it will store the LLM output as a message, and the tool call output as another message. Use this if you want a higher-level view of what has happened - but not every log will be transcripted by this method."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Tools"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "A tool is an atomic function to be used by an agent. To be used by an LLM, it also needs a few attributes that constitute its API and will be used to describe to the LLM how to call this tool:\n",
    "- A name\n",
    "- A description\n",
    "- Input types and descriptions\n",
    "- An output type\n",
    "\n",
    "You can for instance check the [PythonInterpreterTool](https://huggingface.co/docs/smolagents/main/en/reference/default_tools#smolagents.PythonInterpreterTool): it has a name, a description, input descriptions, an output type, and a `forward` method to perform the action.\n",
    "\n",
    "When the agent is initialized, the tool attributes are used to generate a tool description which is baked into the agent's system prompt. This lets the agent know which tools it can use and why.\n",
    "\n",
    "**Schema Information**: For tools that have an `output_schema` defined (such as MCP tools with structured output), the `CodeAgent` system prompt automatically includes the JSON schema information. This helps the agent understand the expected structure of tool outputs and access the data appropriately."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Default toolbox"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "If you install `smolagents` with the \"toolkit\" extra, it comes with a default toolbox for empowering agents, that you can add to your agent upon initialization with argument `add_base_tools=True`:\n",
    "\n",
    "- **DuckDuckGo web search***: performs a web search using DuckDuckGo browser.\n",
    "- **Python code interpreter**: runs your LLM generated Python code in a secure environment. This tool will only be added to [ToolCallingAgent](https://huggingface.co/docs/smolagents/main/en/reference/agents#smolagents.ToolCallingAgent) if you initialize it with `add_base_tools=True`, since code-based agent can already natively execute Python code\n",
    "- **Transcriber**: a speech-to-text pipeline built on Whisper-Turbo that transcribes an audio to text.\n",
    "\n",
    "You can manually use a tool by calling it with its arguments."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# !pip install 'smolagents[toolkit]'\n",
    "from smolagents import WebSearchTool\n",
    "\n",
    "search_tool = WebSearchTool()\n",
    "print(search_tool(\"Who's the current president of Russia?\"))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Create a new tool"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "You can create your own tool for use cases not covered by the default tools from Hugging Face.\n",
    "For example, let's create a tool that returns the most downloaded model for a given task from the Hub.\n",
    "\n",
    "You'll start with the code below."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from huggingface_hub import list_models\n",
    "\n",
    "task = \"text-classification\"\n",
    "\n",
    "most_downloaded_model = next(iter(list_models(filter=task, sort=\"downloads\", direction=-1)))\n",
    "print(most_downloaded_model.id)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "This code can quickly be converted into a tool, just by wrapping it in a function and adding the `tool` decorator:\n",
    "This is not the only way to build the tool: you can directly define it as a subclass of [Tool](https://huggingface.co/docs/smolagents/main/en/reference/tools#smolagents.Tool), which gives you more flexibility, for instance the possibility to initialize heavy class attributes.\n",
    "\n",
    "Let's see how it works for both options:\n",
    "\n",
    "<hfoptions id=\"build-a-tool\">\n",
    "<hfoption id=\"Decorate a function with @tool\">"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from smolagents import tool\n",
    "\n",
    "@tool\n",
    "def model_download_tool(task: str) -> str:\n",
    "    \"\"\"\n",
    "    This is a tool that returns the most downloaded model of a given task on the Hugging Face Hub.\n",
    "    It returns the name of the checkpoint.\n",
    "\n",
    "    Args:\n",
    "        task: The task for which to get the download count.\n",
    "    \"\"\"\n",
    "    most_downloaded_model = next(iter(list_models(filter=task, sort=\"downloads\", direction=-1)))\n",
    "    return most_downloaded_model.id"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The function needs:\n",
    "- A clear name. The name should be descriptive enough of what this tool does to help the LLM brain powering the agent. Since this tool returns the model with the most downloads for a task, let's name it `model_download_tool`.\n",
    "- Type hints on both inputs and output\n",
    "- A description, that includes an 'Args:' part where each argument is described (without a type indication this time, it will be pulled from the type hint). Same as for the tool name, this description is an instruction manual for the LLM powering your agent, so do not neglect it.\n",
    "\n",
    "All these elements will be automatically baked into the agent's system prompt upon initialization: so strive to make them as clear as possible!\n",
    "\n",
    "> [!TIP]\n",
    "> This definition format is the same as tool schemas used in `apply_chat_template`, the only difference is the added `tool` decorator: read more on our tool use API [here](https://huggingface.co/blog/unified-tool-use#passing-tools-to-a-chat-template).\n",
    "\n",
    "\n",
    "Then you can directly initialize your agent:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from smolagents import CodeAgent, InferenceClientModel\n",
    "agent = CodeAgent(tools=[model_download_tool], model=InferenceClientModel())\n",
    "agent.run(\n",
    "    \"Can you give me the name of the model that has the most downloads in the 'text-to-video' task on the Hugging Face Hub?\"\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "</hfoption>\n",
    "<hfoption id=\"Subclass Tool\">"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from smolagents import Tool\n",
    "\n",
    "class ModelDownloadTool(Tool):\n",
    "    name = \"model_download_tool\"\n",
    "    description = \"This is a tool that returns the most downloaded model of a given task on the Hugging Face Hub. It returns the name of the checkpoint.\"\n",
    "    inputs = {\"task\": {\"type\": \"string\", \"description\": \"The task for which to get the download count.\"}}\n",
    "    output_type = \"string\"\n",
    "\n",
    "    def forward(self, task: str) -> str:\n",
    "        most_downloaded_model = next(iter(list_models(filter=task, sort=\"downloads\", direction=-1)))\n",
    "        return most_downloaded_model.id"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The subclass needs the following attributes:\n",
    "- A clear `name`. The name should be descriptive enough of what this tool does to help the LLM brain powering the agent. Since this tool returns the model with the most downloads for a task, let's name it `model_download_tool`.\n",
    "- A `description`. Same as for the `name`, this description is an instruction manual for the LLM powering your agent, so do not neglect it.\n",
    "- Input types and descriptions\n",
    "- Output type\n",
    "All these attributes will be automatically baked into the agent's system prompt upon initialization: so strive to make them as clear as possible!\n",
    "\n",
    "\n",
    "Then you can directly initialize your agent:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from smolagents import CodeAgent, InferenceClientModel\n",
    "agent = CodeAgent(tools=[ModelDownloadTool()], model=InferenceClientModel())\n",
    "agent.run(\n",
    "    \"Can you give me the name of the model that has the most downloads in the 'text-to-video' task on the Hugging Face Hub?\"\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "</hfoption>\n",
    "</hfoptions>\n",
    "\n",
    "You get the following logs:\n",
    "```text\n",
    "╭──────────────────────────────────────── New run ─────────────────────────────────────────╮\n",
    "│                                                                                          │\n",
    "│ Can you give me the name of the model that has the most downloads in the 'text-to-video' │\n",
    "│ task on the Hugging Face Hub?                                                            │\n",
    "│                                                                                          │\n",
    "╰─ InferenceClientModel - Qwen/Qwen2.5-Coder-32B-Instruct ───────────────────────────────────────────╯\n",
    "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ Step 0 ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n",
    "╭─ Executing this code: ───────────────────────────────────────────────────────────────────╮\n",
    "│   1 model_name = model_download_tool(task=\"text-to-video\")                               │\n",
    "│   2 print(model_name)                                                                    │\n",
    "╰──────────────────────────────────────────────────────────────────────────────────────────╯\n",
    "Execution logs:\n",
    "ByteDance/AnimateDiff-Lightning\n",
    "\n",
    "Out: None\n",
    "[Step 0: Duration 0.27 seconds| Input tokens: 2,069 | Output tokens: 60]\n",
    "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ Step 1 ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n",
    "╭─ Executing this code: ───────────────────────────────────────────────────────────────────╮\n",
    "│   1 final_answer(\"ByteDance/AnimateDiff-Lightning\")                                      │\n",
    "╰──────────────────────────────────────────────────────────────────────────────────────────╯\n",
    "Out - Final answer: ByteDance/AnimateDiff-Lightning\n",
    "[Step 1: Duration 0.10 seconds| Input tokens: 4,288 | Output tokens: 148]\n",
    "Out[20]: 'ByteDance/AnimateDiff-Lightning'\n",
    "```\n",
    "\n",
    "> [!TIP]\n",
    "> Read more on tools in the [dedicated tutorial](https://huggingface.co/docs/smolagents/main/en/./tutorials/tools#what-is-a-tool-and-how-to-build-one)."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Multi-agents"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Multi-agent systems have been introduced with Microsoft's framework [Autogen](https://huggingface.co/papers/2308.08155).\n",
    "\n",
    "In this type of framework, you have several agents working together to solve your task instead of only one.\n",
    "It empirically yields better performance on most benchmarks. The reason for this better performance is conceptually simple: for many tasks, rather than using a do-it-all system, you would prefer to specialize units on sub-tasks. Here, having agents with separate tool sets and memories allows to achieve efficient specialization. For instance, why fill the memory of the code generating agent with all the content of webpages visited by the web search agent? It's better to keep them separate.\n",
    "\n",
    "You can easily build hierarchical multi-agent systems with `smolagents`.\n",
    "\n",
    "To do so, just ensure your agent has `name` and`description` attributes, which will then be embedded in the manager agent's system prompt to let it know how to call this managed agent, as we also do for tools.\n",
    "Then you can pass this managed agent in the parameter managed_agents upon initialization of the manager agent.\n",
    "\n",
    "Here's an example of making an agent that managed a specific web search agent using our native [WebSearchTool](https://huggingface.co/docs/smolagents/main/en/reference/default_tools#smolagents.WebSearchTool):"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from smolagents import CodeAgent, InferenceClientModel, WebSearchTool\n",
    "\n",
    "model = InferenceClientModel()\n",
    "\n",
    "web_agent = CodeAgent(\n",
    "    tools=[WebSearchTool()],\n",
    "    model=model,\n",
    "    name=\"web_search_agent\",\n",
    "    description=\"Runs web searches for you. Give it your query as an argument.\"\n",
    ")\n",
    "\n",
    "manager_agent = CodeAgent(\n",
    "    tools=[], model=model, managed_agents=[web_agent]\n",
    ")\n",
    "\n",
    "manager_agent.run(\"Who is the CEO of Hugging Face?\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "> [!TIP]\n",
    "> For an in-depth example of an efficient multi-agent implementation, see [how we pushed our multi-agent system to the top of the GAIA leaderboard](https://huggingface.co/blog/beating-gaia)."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Talk with your agent and visualize its thoughts in a cool Gradio interface"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "You can use `GradioUI` to interactively submit tasks to your agent and observe its thought and execution process, here is an example:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from smolagents import (\n",
    "    load_tool,\n",
    "    CodeAgent,\n",
    "    InferenceClientModel,\n",
    "    GradioUI\n",
    ")\n",
    "\n",
    "# Import tool from Hub\n",
    "image_generation_tool = load_tool(\"m-ric/text-to-image\", trust_remote_code=True)\n",
    "\n",
    "model = InferenceClientModel(model_id=model_id)\n",
    "\n",
    "# Initialize the agent with the image generation tool\n",
    "agent = CodeAgent(tools=[image_generation_tool], model=model)\n",
    "\n",
    "GradioUI(agent).launch()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Under the hood, when the user types a new answer, the agent is launched with `agent.run(user_request, reset=False)`.\n",
    "The `reset=False` flag means the agent's memory is not flushed before launching this new task, which lets the conversation go on.\n",
    "\n",
    "You can also use this `reset=False` argument to keep the conversation going in any other agentic application.\n",
    "\n",
    "In gradio UIs, if you want to allow users to interrupt a running agent, you could do this with a button that triggers method `agent.interrupt()`.\n",
    "This will stop the agent at the end of its current step, then raise an error."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Next steps"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Finally, when you've configured your agent to your needs, you can share it to the Hub!"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "agent.push_to_hub(\"m-ric/my_agent\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Similarly, to load an agent that has been pushed to hub, if you trust the code from its tools, use:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "agent.from_hub(\"m-ric/my_agent\", trust_remote_code=True)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "For more in-depth usage, you will then want to check out our tutorials:\n",
    "- [the explanation of how our code agents work](https://huggingface.co/docs/smolagents/main/en/./tutorials/secure_code_execution)\n",
    "- [this guide on how to build good agents](https://huggingface.co/docs/smolagents/main/en/./tutorials/building_good_agents).\n",
    "- [the in-depth guide for tool usage](https://huggingface.co/docs/smolagents/main/en/./tutorials/building_good_agents)."
   ]
  }
 ],
 "metadata": {},
 "nbformat": 4,
 "nbformat_minor": 4
}
